import axios from 'axios'
import {getToken} from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  responseType: 'arraybuffer'
})

service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
  console.log(error)
})

service.interceptors.response.use(resp => {
  const headers = resp.headers;
  let reg = RegExp(/application\/json/);
  if (headers['content-type'].match(resp.data)) {
    resp.data = unitToString(resp.data);
  } else {
    let fileDownload = require('js-file-download');
    let fileName = headers['content-disposition'].split(";")[1].split('filename=')[1];
    let contentType = headers['content_type'];
    fileName = decodeURIComponent(fileName);
    fileDownload(resp.data, fileName, contentType)
  }
}, error => {
  console.log(error)
})

function unitToString(unitArray) {
  let encodeString = String.fromCharCode.apply(null, new Uint8Array(unitArray));
  let decodeString = decodeURIComponent(escape(encodeString));
  return JSON.parse(decodeString);
}

let base = ''
export const downloadRequest = (url,params) => {
  return service({
    method:'get',
    url:'${base}${url}',
    data:params
  })
}

export default service;
